class Solution:
    def maxProduct(self, nums: list) -> int:
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        self.nums, self.res, mid_res, = nums, -float("inf"), nums[0] or 1
        start_num = bool(nums[0] == 0)
        for i in range(1, len(nums)):
            if nums[i] != 0:
                mid_res *= nums[i]
            else:
                if mid_res > 0:
                    if nums[i-1] != 0:
                        self.res = max(self.res, mid_res)
                elif mid_res < 0:
                    self.find(start_num, i, mid_res)
                mid_res, start_num = 1, i+1
        else:
            if nums[-1] != 0:
                self.find(start_num, i+1, mid_res)
        if self.res < 0:
            self.res = max(nums)
        return int(self.res)

    def find(self, start_num, i, mid_res):
        j, mid_res2 = i - 1, mid_res
        while j > start_num:
            if mid_res < 0:
                mid_res /= self.nums[j]
            if mid_res2 < 0:
                mid_res2 /= self.nums[start_num + i - j - 1]
            j -= 1
        self.res = max(mid_res, mid_res2, self.res)


class Solution2:
    def maxProduct(self, nums):
        nums_r = nums[::-1]
        for i in range(1, len(nums)):
            nums[i] *= nums[i - 1] or 1
            nums_r[i] *= nums_r[i - 1] or 1
        return max(max(nums), max(nums_r))


a = Solution2()
print(a.maxProduct([2, 3, -2, 4]))  # 6
print(a.maxProduct([2, 3, -2, 8]))  # 8
print(a.maxProduct([-2, 0, -1]))  # 0
print(a.maxProduct([-2, -3, -1, -5]))  # 30
print(a.maxProduct([0, 0, 0, 0]))  # 0
print(a.maxProduct([2]))  # 2
print(a.maxProduct([-2]))  # -2
print(a.maxProduct([-1, -1]))  # 1
print(a.maxProduct([0, 2]))  # 2
print(a.maxProduct([0, 2, 2]))  # 4
print(a.maxProduct([-1, 0, -1]))  # 0
